// popup.js
document.addEventListener('DOMContentLoaded', async () => {
    const autoExtractToggle = document.getElementById('autoExtractToggle');
    const autoWrapToggle = document.getElementById('autoWrapToggle');
    const recordButton = document.getElementById('recordButton');

    // 读取开关设置
    const settings = await chrome.storage.local.get({
        autoExtractEnabled: true,
        autoWrapEnabled: false
    });
    autoExtractToggle.checked = settings.autoExtractEnabled;
    autoWrapToggle.checked = settings.autoWrapEnabled;

    // 读取录制状态
    let isRecording = false;
    chrome.runtime.sendMessage({ action: "getRecordingStatus" }, (response) => {
        isRecording = response?.isRecording || false;
        updateRecordButton(isRecording);
    });

    // 开关事件
    autoExtractToggle.addEventListener('change', () => {
        chrome.storage.local.set({ autoExtractEnabled: autoExtractToggle.checked });
    });
    autoWrapToggle.addEventListener('change', () => {
        chrome.storage.local.set({ autoWrapEnabled: autoWrapToggle.checked });
    });

    // 录制按钮事件
    recordButton.addEventListener('click', () => {
        if (isRecording) {
            // 停止录制
            chrome.runtime.sendMessage({ action: "stopRecording" }, (response) => {
                if (response?.success) {
                    // 复制结果到剪贴板
                    navigator.clipboard.writeText(response.data).then(() => {
                        // 弹出提示（通过 background 无法直接 showBubble，改用 alert 或通知）
                        alert(`✅ 批量复制成功！\n共 ${response.count} 条记录`);
                    }).catch(() => {
                        alert('❌ 复制失败');
                    });
                }
                isRecording = false;
                updateRecordButton(false);
            });
        } else {
            // 开始录制
            chrome.runtime.sendMessage({ action: "startRecording" });
            isRecording = true;
            updateRecordButton(true);
        }
    });

    function updateRecordButton(recording) {
        if (recording) {
            recordButton.className = 'stop';
            recordButton.textContent = '停止录制';
        } else {
            recordButton.className = 'start';
            recordButton.textContent = '开始录制';
        }
    }
});